package com.lagou.rpc.consumer.proxy;

import cn.hutool.core.lang.ClassScanner;
import com.lagou.rpc.anno.SimpleClient;
import com.lagou.rpc.consumer.common.Host;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class ClientInit implements BeanFactoryPostProcessor {


    private static final String CLIENT_PACKAGE = "com.lagou.rpc.api";

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        Set<Class<?>> classes = ClassScanner.scanPackageByAnnotation(CLIENT_PACKAGE, SimpleClient.class);
        log.info("<ClientInit> classes-{}", classes);
        classes.stream()
                .forEach(clientClass -> {

                    List<Host> services = new ArrayList<>();
                    String url = clientClass.getAnnotation(SimpleClient.class).url();
                    log.info("<ClientInit> clientClass-{} url-{}", clientClass, url);
                    String[] split = url.split(",");
                    for(String s : split){
                        String[] strings = s.split(":");
                        Host host = new Host();
                        host.setIp(strings[0]);
                        host.setPort(Integer.parseInt(strings[1]));
                        services.add(host);
                    }


                    RpcClientProxy rpcClientProxy = new RpcClientProxy(services, clientClass);
                    Object proxy = rpcClientProxy.createProxy();
                    beanFactory.registerSingleton(clientClass.getName(), proxy);
                });
    }
}
